import {Server} from "socket.io";
import {config} from "../config/portConfig.js";
import {httpResult} from "../utils/utils.js";
import {getUserChatList} from "../controllers/userchatlist.js";
import userBaseDao from "../dao/userbaseDB.js";
import userFriendGroupDao from "../dao/userfriendgroupDB.js";
import {getMsgBySessionId, saveMsg, updateMsgStatus} from "../controllers/msg.js";

let io = new Server({cors: true});
const SOCKET_PORT = config.SOCKET_PORT;

io.on('connection', (socket) => {
  socket.on('login', async (data) => {
    console.log(`${data} 登陆了`);
    try {
      socket.user_account = data;
      socket.emit('loginRes', httpResult.success('连接服务器成功！'));
      let userChatList = await getUserChatList(socket.user_account);
      socket.emit('userChatList', userChatList);
      let userInfo = await getUserInfoSocket(socket.user_account);
      socket.emit('userInfo', userInfo);
      let userJoinList = await getUserJoinListSocket(socket.user_account);
      await socketJoinRooms(socket, userJoinList);
      socket.emit('userJoinList', userJoinList);
    } catch (e) {
      socket.emit('loginRes', httpResult(400, "", '连接服务器失败！'));
    }
  });
  socket.on('message', async (data) => {
    broadcastMessageSocket(io, socket, data);
    // io.sockets.in(data.sessionID).emit('messageTo', httpResult.success(data));
  });
  socket.on('recall', async (data) => {
    if (new Date().getTime() - data.timestamp > 2 * 60 * 1000) {
      socket.emit('recallRes', httpResult(400, '', '不能撤回发出超过2分钟的消息！'));
      return;
    }
    recallMessage(io, socket, data);

  });
  socket.on('getNewMessage', async (data) => {
    let startTime = data.startTime;
    let sessionId = data.sessionID;
    let list = await getMsgBySessionId(sessionId, startTime);
    socket.emit('newMessage', httpResult.success(list, ''));

  });
  socket.on('disconnect', (reason) => {
    console.log(reason, io.engine.clientsCount);
  });
});

io.listen(SOCKET_PORT, () => {
  console.log(`Socket serveice is start on ${SOCKET_PORT} PORT!`);
});

const getUserInfoSocket = async (account) => {
  let userInfo = await userBaseDao.getUserBaseInfo(account);
  return httpResult.success(userInfo);
};
const getUserJoinListSocket = async (account) => {
  let userJoinList = await userFriendGroupDao.getUserFriendGroupMember(account);
  return httpResult.success(userJoinList);
};
const socketJoinRooms = async (socket, userJoinList) => {
  let socketJoinList = [];
  if (userJoinList.code === 200) {
    userJoinList.msg.rows.forEach(item => {
      socketJoinList.push(item._session_id);
    });
  }
  socket.join(socketJoinList);
};
const broadcastMessageSocket = async (io, socket, data) => {
  if (data.message === '' || data.message === null || data.message === undefined) {
    return;
  }
  if (socket.user_account !== data.sender) {
    socket.emit('connectError', httpResult(400, '', '连接错误，请刷新重试！'));
    return;
  }
  let result = await saveMsg(data);
  if (!result) {
    socket.emit('sendMsgError', httpResult(400, '', '发送消息错误，请联系管理员！'));
    return;
  }
  io.sockets.in(data.sessionID).emit('messageTo', httpResult.success(data));
};
const recallMessage = async (io, socket, data) => {
  if (!(data.session_id && data.timestamp && data.sender)) {
    return;
  }
  let result = await updateMsgStatus(data);
  if (!result) {
    socket.emit('recallRes', httpResult(400, '', '撤回消息失败，请联系管理员！'));
    return;
  }
  data.status = 1;
  io.sockets.in(data.session_id).emit('recallRes', httpResult.success(data));
};
const getRoomSockets = (io, roomID) => {
  io.of("/").in(roomID).allSockets().then(items => {
    console.log(items.forEach(item => {
      console.log('看看这是啥：' + item);
    }));
  });
};
